﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.Text;

using LanguageConvert.SharpDevConvert;

namespace LanguageConvert {
	public class CLSConverter : IDisposable {
		public enum EnEventType {
			Off,
			On,
			Converting,
			ConvertError,
			Converted
		}
		public class ConvertEventArgs : EventArgs {
			public EnEventType EventType {
				get;
				set;
			}
			public string ConvertedSource {
				get;
				set;
			}
			public string ErrMsg {
				get;
				set;
			}
			public ConvertEventArgs(EnEventType eventType, string convertedSource = "", string errMsg = "") {
				EventType = eventType;
				ConvertedSource = convertedSource;
				ErrMsg = errMsg;
			}
		}
		public delegate void OnOffStatusDelegate(object sender, ConvertEventArgs e);
		public event OnOffStatusDelegate OnOnOffStatused;

		private SharpDevConvert.ConvertServiceSoapClient cs = null;
		public CLSConverter() {
			Init();
		}

		private void Init() {
			if(cs == null) {
				cs = new ConvertServiceSoapClient("ConvertServiceSoap");
				cs.PerformConversionCompleted += cs_PerformConversionCompleted;
				cs.OpenCompleted += cs_OpenCompleted;
			}
			
			if(cs.State != CommunicationState.Opened) {
				cs.OpenAsync();
			}
		}

		void cs_OpenCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) {
			if(!e.Cancelled) {
				if(OnOnOffStatused != null) {
					OnOnOffStatused(this, new ConvertEventArgs(EnEventType.On));
				}
			} else {
				if(OnOnOffStatused != null) {
					OnOnOffStatused(this, new ConvertEventArgs(EnEventType.Off));
				}
				Debug.WriteLine("Open Cancelled");
			}
		}

		void cs_PerformConversionCompleted(object sender, PerformConversionCompletedEventArgs e) {
			if(e.Result) {
				if(OnOnOffStatused != null) {
					OnOnOffStatused(this, new ConvertEventArgs(EnEventType.Converted, e.ConvertedCode));
				}
			} else {
				if(OnOnOffStatused != null) {
					OnOnOffStatused(this, new ConvertEventArgs(EnEventType.ConvertError, "", e.ErrorMessage));
				}
			}
		}

		public void PerformConversion(string pConType, string pSrcSource) {
			Init();
			cs.PerformConversionAsync(pConType, pSrcSource, true);
			if(OnOnOffStatused != null) {
				OnOnOffStatused(this, new ConvertEventArgs(EnEventType.Converting));
			}
		}

		public void Dispose() {
			try {
				if(cs != null) {
					if(cs.State != CommunicationState.Closed) {
						cs.CloseAsync();
					}
				}
			} catch(Exception ex) {
				Debug.WriteLine(ex.ToString());
			}
		}
	}
}
